/**
 * Created by WYH on 17/4/13.
 */
angular.module('tribalc').service('Api', ['$http', '$state', 'Alert', function ($http, $state, Alert) {

    var status = "debug";
    var CLIENT_BASE_URL = "/tribalc/v1.0";

    if (status == 'debug') {
        CLIENT_BASE_URL = "https://dev-app-services.buluo-gs.com/tribalc/v1.0";
        // CLIENT_BASE_URL = "https://app-services.buluo-gs.com/tribalc/v1.0";
        // CLIENT_BASE_URL = "https://localhost:8080/tribalc/v1.0";
    }

    var ALIYUN_URL = "https://buluo-gs-pictures.oss-cn-beijing.aliyuncs.com/";

    var assigned = function () {
        return window.localStorage.assign;
    };

    var headers = function () {
        return {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": localStorage.token
        }
    };


    // function verifyLogin() {
    //     if (!assigned()) {
    //         alert('您还未登录');
    //         $state.go('login');
    //         throw new Error("Exit");
    //     }
    // }


    var http = function (url, method, data, sucFuc, errFuc, notNeedLogin) {
        var req = {
            url: CLIENT_BASE_URL + '/' + url,
            method: method.toUpperCase(),
            headers: headers(),
            data: null
        };
        if ((arguments[1].toUpperCase() == 'POST' || arguments[1].toUpperCase() == 'PUT')) {
            req.data = data;
        } else {
            var temp = sucFuc;
            sucFuc = data;
            errFuc = temp;
        }
        $http(req)
            .then(function successCallback(response) {
                sucFuc(response.data);
            }, function errorCallback(response) {
                if (response.status == 401) {
                    return gotoLogin();
                }
                errFuc ? errFuc(response) : '';
            });

    };

    function gotoLogin() {
        localStorage.clear();
        Alert.alertBox('您的账号在其他地方登陆，请重新登录');
        $state.go('login');

        //throw '未登录';
    }

    //倒计时
    function sendVerification(element) {

        var wait = 60;
        forbidSendVerification(element);
        function forbidSendVerification(element) {
            if (wait == 0) {
                element.removeAttribute("disabled");
                element.value = "获取验证码";
                wait = 60;
            } else {
                element.setAttribute("disabled", true);
                element.value = "重新发送(" + wait + ")";
                wait--;
                setTimeout(function () {
                    forbidSendVerification(element)
                }, 1000)
            }
        }
    }

    //忘记密码

    function setupForgetPassword(phone, password, vcode, sucFuc, errFuc) {
        var path = "companies/password?phone=" + phone + "&vcode=" + vcode;
        data = {
            "value": password
        };
        http(path, 'put', data, sucFuc, errFuc);
    }

    //获取公司锁权限认证
    function getCompanylockAuthorized(id, torF, sucFuc, errFuc) {
        var path = "companies?me=" + id + "?&lockAuthorized=" + torF;
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result)
            } else if (result.code == 403) {
                Alert.alertBox('无权限操作')
            }
        }, function (result) {
        });
    }

    this.getCompanylockAuthorized = getCompanylockAuthorized;


    // 验证码资源

    function sendPhoneVerifyCode(phone, sucFuc, errFuc) {
        var data = {
            'value': phone
        };
        var path = 'verifications/phone';
        http(path, 'post', data, function (result) {
            if (result.code == 202) {
                sendVerification(document.getElementById('sms'))
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox('手机号码格式错误');
            } else {
                Alert.alertBox('发送验证码失败,失败原因：' + result.message);
            }
        }, function (error) {
            error ? errFuc(error) : '';
        });
    }


    function uploadPicture(contentMD5, id, sucFuc, errFuc) {
        var path = "oss_authorization/picture?me=" + id;
        var picName = Date.parse(new Date())+"web_image.jpg";
        var data = {
            key: picName,
            contentType: 'image/jpeg',
            contentMD5: contentMD5
        };
        http(path, 'post', data, function (result) {
            sucFuc(result)
        }, function (error) {
            error ? errFuc(error) : '';
        })
    }
    function uploadLogoPicture(contentMD5, id, sucFuc, errFuc) {
        var path = "oss_authorization/picture?me=" + id;
        var picName = "icon.jpg";
        var data = {
            key: picName,
            contentType: 'image/jpeg',
            contentMD5: contentMD5
        };
        http(path, 'post', data, function (result) {
            sucFuc(result)
        }, function (error) {
            error ? errFuc(error) : '';
        })
    }

    function getVerificationsPicture(sucFuc) {
        var path= CLIENT_BASE_URL + "/verifications/picture";//todo
        // var eleAppend = document.getElementById("verfication");
        window.URL = window.URL || window.webkitURL;
        if (typeof history.pushState == "function") {
            var xhr = new XMLHttpRequest();
            xhr.open("get", path, true);
            xhr.responseType = "blob";
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.setRequestHeader("Accept",  "application/json");
            xhr.onload = function () {
                if (this.status == 200) {

                    var blob = this.response;

                    // var img = document.createElement("img");
                    // img.onload = function () {
                    //     window.URL.revokeObjectURL(img.src); // 清除释放
                    // };
                    // img.src = window.URL.createObjectURL(blob);
                    var url=window.URL.createObjectURL(blob);
                    var head=this.getResponseHeader('Authorization');
                    sucFuc(url,head)
                    // eleAppend.appendChild(img);
                }
            };

            xhr.send();

        }
    }


    this.getVerificationsPicture = getVerificationsPicture;

    // objectkey和putUrl参数根据上传图片接口获得
    function callAliyunPicture(objectkey, putUrl, file, sucFuc) {
        putUrl = 'https' + putUrl.substring(putUrl.indexOf('://'));
        var imageUrl = ALIYUN_URL + objectkey;
        var xhr = new XMLHttpRequest();
        xhr.open('PUT', putUrl, true);
        xhr.setRequestHeader("Content-Type", "image/jpeg");
        xhr.onload = function () {
            if (xhr.status == 200) {
                sucFuc(imageUrl);
            } else {
                Alert.alertBox('图片上传失败');
            }
        };
        xhr.send(file);
    }

    /* 上传excel */
    function uploadExcel(file, sucFuc, errFuc) {
        var url = CLIENT_BASE_URL + "/companies/" + assigned() + "/staffs/batch";
        var form = new FormData();
        form.append("file", file);// 文件对象
        var token = window.localStorage.token;
        // XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();
        xhr.open("post", url, true);
        xhr.setRequestHeader('Authorization', token);
        xhr.onload = function () {
            if (xhr.status == 200) {
                sucFuc();
            } else {
                errFuc();
            }
        };
        xhr.send(form);
    }

    this.uploadExcel = uploadExcel;


    // 公司资源

    function login(phone, password, sucFuc, errFuc) {
        var path = "companies/" + "login";
        var data = {
            "phone": phone,
            "password": password
        };
        http(path, 'post', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox('用户名或密码错误');
            } else {
                Alert.alertBox('登录失败, ' + result.message | '');
            }
        }, function (error) {
            Alert.alertBox('登录失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        }, true)
    }


    function getCompanyDetail(id, sucFuc, errFuc) {
        var companyId = id ? id : window.localStorage.assign;
        var path = "companies/" + companyId;
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('获取公司信息失败, 没有找到该公司');
            }
        }, function (error) {
            Alert.alertBox('获取公司信息失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        });
    }


    /**
     * 删除员工
     * @param staffIds 员工id数组
     * @param suf
     * @param errf
     * */
    function deleteStaff(staffIds, suf, errf) {
        var staffidUrl = 'companies/' + assigned() + '/staffs/';
        staffIds.forEach(function (value, index) {
            staffidUrl = staffidUrl + (index == staffIds.length - 1 ? value.id : value.id + ',');
        });
        // console.log((index == staffIds.length - 1 ? value.id : value.id + ','))
        http(staffidUrl, 'delete', function (response) {
            console.log(response)
            if (response.code == 204) {
                suf(response);
            } else if (response == 403) {
                Alert.alertBox('删除失败,无权限删除')
            } else if (response == 404) {
                Alert.alertBox('删除失败,公司信息或员工信息未找到')
            } else {
                Alert.alertBox('删除失败：' + response.massage)
            }
        }, function (response) {
            Alert.alertBox('删除失败')
            errf ? errf(response) : '';
        })
    }


    function resetPassword(oldPassword, newPassword, sucFuc, errFuc) {
        var path = 'companies/' + assigned() + '/password';
        var data = {
            "password": oldPassword,
            "newPassword": newPassword
        };
        http(path, 'put', data, function (response) {
            if (response.code == 200) {
                sucFuc(response);
            } else if (response.code == 409) {
                Alert.alertBox('重置密码失败,旧密码错误');
            } else {
                Alert.alertBox('重置密码失败, 错误原因:' + response.message);
            }
        }, function (error) {
            Alert.alertBox('重置密码失败,服务器错误');
            errFuc ? errFuc(error) : '';
        });
    }


    function changeCompanyPhone(newPhone, verifyCode, sucFuc, errFuc) {
        var path = "companies/" + assigned() + "/phone";
        var data = {
            phone: newPhone,
            verificationCode: verifyCode
        };
        var message = '修改手机号码失败';
        http(path, 'put', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox(message + ',手机号码格式错误');
            } else if (result.code == 401) {
                Alert.alertBox(message + ',手机验证码不匹配');
            } else if (result.code == 404) {
                Alert.alertBox(message + ',未找到用户敏感信息');
            } else if (result.code == 409) {
                Alert.alertBox(message + ',新手机号已存在');
            } else {
                Alert.alertBox(message + ',' + result.message);
            }
        }, function (error) {
            Alert.alertBox(message + ',服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function register(companyModel, sucFuc, errFuc, boolen) {
        var path = 'companies/registry';
        var data = boolen ? companyModel : companyModel.getObject();
        // var data = companyModel.getObject();
        var message = '注册失败';
        http(path, 'post', data, function (result) {
            if (result.code == 201) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox(message + ",手机格式不正确");
            } else if (result.code == 507) {
                Alert.alertBox(message + ',服务器保存失败');
            } else if (result.code == 401) {
                Alert.alertBox(message + ',手机验证码不匹配');
            } else if (result.code == 409) {
                Alert.alertBox(message + ',该公司已注册');
            } else {
                Alert.alertBox(message + ',' + result.message);
            }
        }, function (error) {
            Alert.alertBox(message + ',服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    function getCompanyList(communityId, sucFuc, errFuc) {
        var path = 'companies?communityId=' + communityId + "&type=company";
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('获取公司列表失败，找不到该社区的公司信息');
            } else {
                Alert.alertBox('获取公司列表失败,');
            }
        }, function (error) {
            Alert.alertBox('获取公司列表失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function perfectCompanyInfo(companyModel, sucFuc, errFuc) {
        var keyPath = "";
        var object = companyModel.getObject();
        Object.keys(object).forEach(function (key, index) {
            if (index == 0) {
                keyPath += key;
            } else {
                keyPath += "," + key;
            }
        });
        var path = "companies/" + assigned() + "/" + keyPath;
        http(path, 'put', object, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox('完善失败,字段不存在');
            } else if (result.code == 404) {
                Alert.alertBox('完善失败,没有找到公司');
            } else if (result.code == 507) {
                Alert.alertBox('完善失败,修改失败');
            } else {
                Alert.alertBox('完善失败,失败原因:' + result.message);
            }
        }, function (result) {
            Alert.alertBox('完善失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })

    }

    // 福利 -- 员工信息
    function getWelfareStaffList(contidion, limitSize, sortSkip, sucFuc, errFuc) {
        if (contidion != null) {
            contidion = contidion.indexOf(":") == -1 ? contidion : "condition=" + contidion;
        } else {
            contidion = "";
        }
        limitSize = limitSize == null ? "" : "&limitSize=" + limitSize;
        sortSkip = sortSkip == null ? "" : "&sortSkip=" + sortSkip;
        var path = "companies/" + assigned() + "/staffs/binded?" + contidion + limitSize + sortSkip;
        http(path, 'get', function (result) {
            console.log(result)
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取员工列表失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取员工列表失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }
    function getWelfareWalletInfo(id,sucFuc,errFuc)
    {
        id = id==null ? assigned() : id;
       var path = "wallets/"+id+"?me="+assigned();
       http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取用户钱包信息失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取用户钱包信息失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }
    function getWelfareList(paymentID,pageNum,pageSize,sucFuc,errFuc)
    {
        pageNum = pageNum == null? "" : "&pageNum="+pageNum;
        pageSize = pageSize == null ? "" : "&pageSize="+pageSize ;
        paymentID = paymentID == null ? assigned() : paymentID;

        var path = "wallets/"+paymentID+"/payments?me="+assigned()+"&type=WELFARE"+pageNum+pageSize;
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取福利列表失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取福利列表失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    function getWelfareDetail(paymentID,sucFuc,errFuc)
    {
        paymentID = paymentID == null ? assigned() : paymentID;
        var path = "payments/"+paymentID+"/routers?me="+assigned()+"&type=welfare";
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取福利详情失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取福利详情失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }
    this.getWelfareDetail = getWelfareDetail;

    function creatWelfare(welfaremodel,id,sucFuc) {
        console.log(welfaremodel)
        var data = welfaremodel
        id = id == null ? assigned() : id;
        console.log(id)
        var path = "wallets/"+id+"/payments?me="+assigned()+"&type=welfare";
        http(path,'post',data,function (result) {
            console.log(result)

            if(result.code === 200){
                sucFuc(result)
            }else if(result.code === 401){
                Alert.alertBox('支付密码错误')
            }else if(result.code === 423){
                Alert.alertBox('账户已锁定')
            }else if(result.code === 424){
                Alert.alertBox('余额不足')
            }
        })
    }

    // 公司资源 -- 员工信息

    function getStaffList(contidion, limitSize, sortSkip, sucFuc, errFuc) {
        if (contidion != null) {
            contidion = contidion.indexOf(":") == -1 ? contidion : "condition=" + contidion;
        } else {
            contidion = "";
        }
        limitSize = limitSize == null ? "" : "&limitSize=" + limitSize;
        sortSkip = sortSkip == null ? "" : "&sortSkip=" + sortSkip;
        var path = "companies/" + assigned() + "/staffs?" + contidion + limitSize + sortSkip;
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取员工列表失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取员工列表失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function addStaff(staffModel, sucFuc, errFuc) {
        var path = "companies/" + assigned() + "/staffs";
        var data = staffModel.getAddObject();
        http(path, 'post', data, function (result) {
            if (result.code == 201) {
                sucFuc(result);
            } else {
                Alert.alertBox('添加公司员工失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('添加公司员工失败, 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function modifyStaff(staffId, staffModel, sucFuc, errFuc) {
        var data = staffModel.getObject();
        var keyPath = "";
        Object.keys(data).forEach(function (key, index) {
            if (index == 0) {
                keyPath += key;
            } else {
                keyPath += "," + key
            }
        });
        var path = "companies/" + assigned() + "/staffs/" + staffId + "/" + keyPath;
        var message = '修改员工信息失败';
        http(path, 'put', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox(message + ',公司员工信息未找到');
            } else if (result.code == 400) {
                Alert.alertBox(message + ',找不到字段');
            } else if (result.code == 403) {
                Alert.alertBox(message + ',没有操作权限');
            } else if (result.code == 507) {
                Alert.alertBox(message + ',员工信息更新失败');
            } else {
                Alert.alertBox(message + ',' + result.message);
            }
        }, function (error) {
            Alert.alertBox(message + ', 服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    function setManagestaff(staffId,sucFuc) {
        var path = "companies/" + assigned() + "/staffs/" + staffId + "/administrator_application";
        http(path,'put',null,function (result) {
            if( result.code == 200)
            {
                sucFuc(result);
            }else  if(result.code == 507){
                Alert.alertBox('服务器保存失败');
            }else{
                Alert.alertBox('未知异常');
            }
        })
    }


    // 门锁设备资源


    function getAuthLocksList(sucFuc, errFuc) {
        var path = "locks?me=" + assigned() + "&type=company";
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取门锁设备失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取门锁设备失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function getOwnLocksList(sucFuc, errFuc) {
        var path = "locks?me=" + assigned() + "&type=p";
    }


    function createLock(lockModel, sucFuc, errFuc) {
        var path = 'locks?me=' + assigned() + '&type=company';
        var data = lockModel.getObject();
        http(path, 'post', data, function (result) {
            if (result.code == 201) {
                sucFuc();
            } else if (result.code == 403) {
                Alert.alertBox('创建设备失败，无操作权限');
            }
        }, function (error) {
            Alert.alertBox('创建设备失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    function modifyLock(lockModel, sucFuc, errFuc) {
        var path = 'locks/' + lockModel.id + "?me=" + assigned() + '&type=company';
        var data = lockModel.getObject();
        var message = '修改设备失败';
        http(path, 'put', data, function (result) {
            var code = result.code;
            if (code == 200) {
                sucFuc(result);
            } else if (code == 403) {
                Alert.alertBox(message + ',无操作权限');
            } else if (code == 404) {
                Alert.alertBox(message + '未找到设备');
            } else if (code == 507) {
                Alert.alertBox(message + '服务器保存失败');
            }
        }, function (error) {
            Alert.alertBox(message + '服务器错误');
        })
    }


    function deleteLock(id, sucFuc, errFuc) {
        var path = 'locks/' + id + "?me=" + assigned() + '&type=company';
        http(path, 'delete', function (result) {
            if (result.code == 204) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('删除设备失败，未找到设备信息');
            } else if (result.code == 403) {
                Alert.alertBox('删除设备失败，无操作权限');
            } else {
                Alert.alertBox('删除设备失败');
            }
        }, function (error) {
            Alert.alertBox('删除设备失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function getAuthAndUnAuthCompanyList(lockId, sucFuc, errFuc) {
        var path = 'locks/' + lockId + '/auth_status?me=' + assigned() + '&type=company';
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 403) {
                Alert.alertBox('获取授权公司失败，无权限操作');
            } else {
                Alert.alertBox('获取授权公司失败，失败原因：' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取授权公司失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function lockAuthCompany(lockId, companyIdArr, sucFuc, errFuc) {
        var path = 'locks/' + lockId + '/auth?me=' + assigned() + '&type=company';
        http(path, 'put', companyIdArr, function (result) {

            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox('失败，传入公司ID不匹配');
            } else if (result.code == 404) {
                Alert.alertBox('失败，未找到设备信息');
            } else if (result.code == 403) {
                Alert.alertBox('失败，不是本社区公司不能被授锁权限');
            } else {
                Alert.alertBox('失败，失败原因：' + result.message);
            }
        }, function (error) {
            Alert.alertBox('授权失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function setupCompanyLockAuth(companyId, isAuth, sucFuc, errFuc) {
        var path = 'locks/auth/' + companyId + '?me=' + assigned();
        var data = {
            value: isAuth
        };
        http(path, 'put', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('授权失败,失败原因：' + result.message);
            }
        }, function (error) {
            Alert.alertBox('授权失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }
    function setUpRentManageAuth(isAuth,equipID,sucFuc,errFuc) {
        var path = "locks/auth/"+assigned()+"/guest?me=" + assigned();
        var data = {
            value: equipID,  //门锁ID
            switcher: isAuth
        };
        console.log(path);
        http(path, 'put', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            }
            else if (result.code == 403)
            {
                return Alert.alertBox('访客授权失败,失败原因：' + "无操作权限");
            }
            else if (result.code == 404)
            {
                return Alert.alertBox('访客授权失败,失败原因：' + "未找到设备");
            }
            else if (result.code == 409)
            {
                return Alert.alertBox('访客授权失败,失败原因：' + "设备状态冲突");
            }
            else if (result.code == 507)
            {
                return Alert.alertBox('访客授权失败,失败原因：' + "服务器保存失败");
            }
        }, function (error) {
            Alert.alertBox('访客授权失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    //
    function setManageAuthor(manageID,sucFuc,errFuc) {
        var path=''+manageID
        var data={
        }
        http(path,'put',function (result) {
            if (result.code ==200){
                sucFuc();
            }
        },function (error) {
            errFuc?errFuc(error):'';
        })
    }
    this.setManageAuthor=setManageAuthor;


    //物业公司认证普通公司
    function approveCompany(companyID,sucFuc,errFuc) {
        // /companies/{id}/autherization?me={物业公司ID}&targetCompanyId={被认证的普通公司}
        var path = "companies/"+companyID+"/autherization?me="+assigned();
        console.log(path);
        http(path,'put',{},function (result) {
            console.log(result);
            if (result.code ==200){
                sucFuc();
            }
            else
            {

            }
        },function (error) {
            errFuc?errFuc(error):'';
        })
    }


    //获取物业公司管理的公司列表
    function getCompanies(limitSize,sortSkip,sort,sucFuc,errFuc)
    {
        limitSize = limitSize == null ? "" : "&limitSize=" + limitSize;
        sortSkip = sortSkip == null ? "" : "&sortSkip=" + sortSkip;

        var path = "companies?me="+assigned()+"&sort=registrationDate, "+sort+limitSize+sortSkip;
        console.log(path)
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取公司列表失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取公司列表失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    // 租赁资源
    function getRentList(communityId, status, limitSize, sortSkip, sort, sucFuc, errFuc) {
        status = status ? '&status=' + status : '';
        limitSize = limitSize ? '&limitSize=' + limitSize : '';
        sortSkip = sortSkip ? "&sortSkip=" + sortSkip : '';
        sort = sort ? "&sort=" + sort : "&sort=beginTime,desc";
        var path = "rent_protocols?me=" + assigned() + "&communityId=" + communityId + status + limitSize + sortSkip + sort;
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('获取租赁协议列表失败,找不到物业公司信息');
            } else if (result.code == 403) {
                Alert.alertBox('获取租赁协议列表失败,无操作权限');
            } else {
                Alert.alertBox('获取租赁协议列表失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取租赁协议列表失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function getRentDeail(companyId, sucFuc, errFuc) {
        companyId = companyId ? companyId : assigned();
        var path = 'rent_protocols?me=' + assigned() + "&ownerId=" + companyId;

        var message = '获取租赁协议失败';
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox(message + ',找不到该物业公司信息');
            } else if (result.code == 403) {
                Alert.alertBox(message + ',无操作权限');
            } else {
                Alert.alertBox(message + ',' + result.message);
            }
        }, function (error) {
            Alert.alertBox(message + ',服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function getRentBuckle(rentID, sucFuc, errFuc) {
        // companyId = companyId ? companyId : assigned();
        // var path = 'buckle_card_info?me=' + assigned() + "&companyId=" + companyId;
        var path = 'rent_protocols/'+rentID+'/withhold?me='+assigned();
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404){
                Alert.alertBox('获取代扣信息失败,失败原因:' + '协议不存在');
            }
        }, function (error) {
            Alert.alertBox('获取代扣信息失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function createBuckle(buckleModel,rentID, sucFuc, errFuc) {
        // var path = 'buckle_card_info?me=' + assigned();
        var path = 'rent_protocols/'+rentID+'/withhold?me='+assigned();
        console.log(path);
        var data = buckleModel.getObject();
        http(path, 'put', data, function (result) {
            console.log(result);
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('创建代扣信息失败，租赁协议不存在');
            } else if (result.code == 400){
                Alert.alertBox('创建代扣信息失败,数据格式不正确');
            }
        }, function (error) {
            Alert.alertBox('创建代扣信息失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    function getRentPayment(companyId, sucFuc, errFuc) {
        companyId = companyId ? companyId : assigned();
        var path = 'rent_payments?me=' + assigned() + "&ownerId=" + companyId;
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('获取缴租信息失败,找不到公司');
            } else if (result.code == 403) {
                Alert.alertBox('获取缴租信息失败,无操作权限');
            } else {
                Alert.alertBox('获取缴租信息失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取缴租信息失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })

    }


    function createRentProtocol(rentProtocol, sucFuc, errFuc) {
        var path = 'rent_protocols?me=' + assigned();
        var data = rentProtocol.getCreateObject();
        
        http(path, 'post', data, function (result) {
            console.log(result);
            if (result.code == 201) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox('创建缴租合同失败,请检查输入内容');
            } else if (result.code == 403) {
                Alert.alertBox('创建缴租合同失败,无操作权限');
            } else {
                Alert.alertBox('创建缴租合同失败' + result.message);
            }
        }, function (error) {
            console.log(error);
            Alert.alertBox('创建缴租合同失败' + '网络链接失败');
            errFuc ? errFuc(error) : '';
        })

    }

    function getRentPlanitemList(companyId, rentId, sucFuc, errFuc) {
        companyId = companyId ? companyId : assigned();
        var path = 'rent_protocols' + '/' + rentId + '/plan_items' + '?me=' + companyId;

        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('获取租赁计划项失败,该公司没有租赁协议');
            } else if (result.code == 403) {
                Alert.alertBox('获取租赁计划项失败,无操作权限');
            } else {
                Alert.alertBox('获取租赁计划项失败,失败原因:' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取租赁计划项失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    /* 企业租户，付款提交 */
    function tenantsSubmitPay(companyId, amount, bankSerialNum, sucFuc, errFuc) {
        companyId = companyId ? companyId : assigned();
        var amounts = amount.toFixed(2)
        var path = "rent_payments?me=" + companyId;
        var data = {
            amount: amounts,
            bankSerialNum: bankSerialNum
        };

        http(path, 'post', data, function (result) {
            if (result.code == 201) {
                sucFuc(result);
            } else if (result.code == 400) {
                Alert.alertBox('付款提交失败，数据格式不正确');
            } else {
                Alert.alertBox('付款提交失败');
            }
        }, function (error) {
            Alert.alertBox('付款提交失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }

    function changeSubmitPay(companyId, amount, bankSerialNum, sucFuc, errFuc) {
        companyId = companyId ? companyId : assigned();
        var path = 'rent_payments/' + companyId + '?me=' + assigned();
        var amounts = amount.toFixed(2)
        var data = {
            amount: amounts,
            bankSerialNum: bankSerialNum
        };

        http(path, 'put', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('修改付款失败，未找到公司');
            } else if (result.code == 403) {
                Alert.alertBox('无操作权限');
            } else if (result.code == 409) {
                Alert.alertBox('修改付款失败,发生冲突');
            } else if (result.code == 500) {
                Alert.alertBox('修改付款失败,服务器内部错误');
            }
        }, function (error) {
            Alert.alertBox('修改付款提交失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function setupRentLockAuth(companyId, isAuth, sucFuc, errFuc) {
        var path = 'locks/auth/' + companyId + '?me=' + assigned();
        var data = {
            value: isAuth
        };
        http(path, 'put', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('失败，失败原因：' + result.message);
            }
        }, function (error) {
            Alert.alertBox('失败，服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function checkRentPayment(rentId, mismatch, bankSerialNum, amount, sucFuc, errFuc) {
        var path = 'rent_payments/' + rentId + '/verify?me=' + assigned();
        var amounts = amount.toFixed(2);
        var data = mismatch ? {
            "mismatch": true,
            "amount": amounts,
            "bankSerialNum": bankSerialNum
        } : {
            "mismatch": false
        };

        http(path, 'put', data, function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                Alert.alertBox('核实失败,未找到该公司');
            } else if (result.code == 403) {
                Alert.alertBox('核实失败,无操作权限');
            } else if (result.code == 409) {
                Alert.alertBox('核实失败,发生冲突');
            } else if (result.code == 500) {
                Alert.alertBox('核实失败,服务器内部错误');
            } else {
                Alert.alertBox('核实失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('核实失败,服务器错误');
        })
    }


    function getCommunityList(sucFuc, errFuc) {
        http('communities', 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取社区列表失败，失败原因：' + result.message);
            }
        }, function (error) {
            Alert.alertBox('获取社区列表失败,服务器错误');
            errFuc ? errFuc(error) : '';
        })
    }


    function getChinaCitysJson(sucFuc) {
        $http({
            url: '/tribalc-web/json/chinaCity.json'
        }).then(function (result) {
            sucFuc(result.data);
        }, function (error) {

        })
    }


    /* 获取企业人员列表 */
    function getCompanyMemberList(companyId, sucFuc, errFuc) {
        companyId = companyId ? companyId : assigned();
        var path = "companies/" + assigned() + '/members?me=' + companyId;
        http(path, 'get', function (result) {
            if (result.code == 200) {
                sucFuc(result);
            } else {
                Alert.alertBox('获取管理员失败');
            }
        }, function (error) {
            Alert.alertBox('获取管理员失败，服务器错误');
        })
    }


    /*公司主动绑定员工*/
    function bindCompanyStaff(value,companyId,sucFuc,errFuc){
        // /companies/{id}/bindAndAuthenticate
        var path = "companies/"+companyId+"/bindAndAuthenticate";
        var data={
            'value':value
        }
        http(path,'post',data,function(result){
            if (result.code == 200) {
                sucFuc(result);
            } else if (result.code == 404) {
                // console.log(result)
                Alert.alertBox('企业或员工或个人不存在');
            } else if (result.code == 409) {
                Alert.alertBox('企业录入员工信息和员工自己个人版录入信息不匹配');
            } else if (result.code == 500) {
                Alert.alertBox('服务器内部错误');
            } else if (result.code == 507) {
                Alert.alertBox('绑定失败');
            } else {
                Alert.alertBox('绑定失败,' + result.message);
            }
        }, function (error) {
            Alert.alertBox('绑定失败,服务器错误');
        })
    }

    function cancleRentprotocol(id,rentName,sucFun) {
        var path = 'rent_protocols/'+ id +'?me='+assigned() + '&ownerName='+ rentName;
        console.log(path)
        http(path,'delete',function (result) {
            console.log(result)
            if(result.code === 204){
                sucFun(result)
            }else if(result.code === 400){
                Alert.alertBox('确认名称输入错误');
            }else if(result.code === 404){
                console.log(result)
                Alert.alertBox('找不到该租赁协议');
            }else if(result.code === 403){
                Alert.alertBox('无操作权限');
            }else if(result.code === 409){
                Alert.alertBox('协议状态冲突');
            }else if(result.code === 507){
                Alert.alertBox('删除失败');
            }
        })
    }
    
    function getRentEndTime(companyId, sucFun){
        
      
        var path = 'rent_protocols' + "?me="+assigned()+"&companyId="+ companyId;
        http(path,'get',function(result){
            if(result.code === 200){
                sucFun(result.data)
            } else if(result.code === 204){
                sucFun(false)
            }else if(result.code === 403){
                Alert.alertBox("无操作权限")
            }else {
                Alert.alertBox("未能捕获异常")
            }

        })
    }


    // 验证码资源

    /**
     * 发送验证码
     * @param phone 手机号码
     * @param sucFuc 成功后的回调函数
     * @param errFuc 失败后的回调函数
     * */
    this.sendPhoneVerifyCode = sendPhoneVerifyCode;


    /**
     * 上传图片
     * @param contentMD5 图片的md5加密
     * @param sucFuc
     * @param errFuc
     **/
    this.uploadPicture = uploadPicture;
    this.uploadLogoPicture = uploadLogoPicture;


    /**
     * 阿里云图片上传
     * */
    this.callAliyunPicture = callAliyunPicture;


    // 公司资源

    /**
     * 登录
     * @param phone 帐号/手机号
     * @param password 密码
     * @param sucFuc
     * @param errFuc
     * */
    this.login = login;


    /**
     * 注册
     * @param companyModel js/service/company 中定义的companyModel
     * @param sucFuc
     * @param errFuc
     * */
    this.register = register;


    /**
     * 获取公司详情
     * @param id 公司assign
     * @param sucFuc
     * @param errFuc
     * */
    this.getCompanyDetail = getCompanyDetail;


    /**
     * 重置密码
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param sucFuc
     * @param errFuc
     * */
    this.resetPassword = resetPassword;
    /**
     * 忘记密码
     * @param phone  预留手机号
     * @param password 密码
     * @param vcode 手机验证码
     */
    this.setupForgetPassword = setupForgetPassword;
    /**
     * 修改手机号码
     * @param newPhone 新手机号
     * @param verifyCode 验证码
     * @param sucFuc
     * @param errFuc
     * */
    this.changeCompanyPhone = changeCompanyPhone;


    /**
     * 完善公司信息
     * @param companyModel
     * */
    this.perfectCompanyInfo = perfectCompanyInfo;


    this.getCompanyList = getCompanyList;


    // 公司资源 -- 员工信息


    /**
     * 获取员工列表
     * @param contidion 查询条件 ，例如“name:王丹”（PS:中间的冒号是英文状态下的）， 支持查询的字段有：name, idNo, phone, department, position, personNum
     * @param limitSize 每页限制条数
     * @param sortSkip 默认查询起步的时间和跳过时间，以逗号分隔，如 1478513563773,3 表示查询晚于时间1478513563773并从跳过前3条记录
     * @param sucFuc
     * @param errFuc
     * */
    this.getStaffList = getStaffList;

    this.getWelfareStaffList = getWelfareStaffList;
    this.getWelfareList = getWelfareList;
    this.creatWelfare = creatWelfare;
    this.getWelfareWalletInfo = getWelfareWalletInfo;

    /**
     * 获取社区列表
     * @param sucFuc
     * @param errFuc
     * */
    this.getCommunityList = getCommunityList;


    /**
     * 添加员工
     * @param staffModel service/model/staff.js中的StaffModel
     * @param sucFuc
     * @param errFuc
     * */
    this.addStaff = addStaff;


    /**
     * 修改员工信息
     * @param staffId 修改的员工id
     * @param staffModel service/model/staff.js中的StaffModel
     * @param sucFuc
     * @param errFuc
     * */
    this.modifyStaff = modifyStaff;
    this.setManagestaff = setManagestaff;

    this.deleteStaff = deleteStaff;


    // 门锁设备资源

    /**
     * 获取已授权的设备列表
     * @param sucFuc
     * @param errFuc
     * */
    this.getAuthLockList = getAuthLocksList;


    /**
     * 获取管理员列表
     * */
    this.getCompanyMemberList = getCompanyMemberList;


    this.createLock = createLock;

    this.modifyLock = modifyLock;

    this.deleteLock = deleteLock;

    this.getAuthAndUnAuthCompanyList = getAuthAndUnAuthCompanyList;

    /**
     * 为设备授权
     * @param lockId 设备id
     * @param companyIdArr 授权公司id组成的数组
     * @param sucFuc
     * @param errFuc
     * */
    this.lockAuthCompany = lockAuthCompany;

    /**
     * 设置租户企业是否拥有锁权限
     * @param companyId 需要设置授权的租户企业id
     * @param isAuth 是否授权 true or false
     * @param sucFuc
     * @param errFuc
     * */
    this.setupCompanyLockAuth = setupCompanyLockAuth;

    /*
     * 修改设备访客权限
     * */
    this.setUpRentManageAuth = setUpRentManageAuth;


    //获取物业公司管理的普通公司
    this.getCompanies = getCompanies;

    //物业公司认证普通公司
    this.approveCompany = approveCompany;

    // 租赁资源


    /**
     * 物业公司获取指定社区的租赁协议列表
     * @param communityId  社区ID
     * @param status  NORMAL|OVERDUE
     * @param limitSize  每页最多数量
     * @param sortSkip
     * @param sort  beginTime,desc
     * @param sucFuc
     * @param errFuc
     * */
    this.getRentList = getRentList;


    /**
     * 获取指定公司租赁协议
     * @param companyId  如果是物业公司，为查询公司的id。非物业公司，填写为null
     * @param sucFuc
     * @param errFuc
     * */
    this.getRentDeail = getRentDeail;


    /**
     * 获取代扣信息
     * @param companyId 查询的公司id
     * @param sucFuc
     * @param errFuc
     * */
    this.getRentBuckle = getRentBuckle;


    /**
     * 为协议公司授权或取消授权
     * @param companyId 需要授权或取消授权的企业ID
     * @param isAuth Boolean 是否授权
     * @param sucFuc
     * @param errFuc
     * */
    this.setupRentLockAuth = setupRentLockAuth;

    this.createBuckle = createBuckle;


    /**
     * 获取缴租信息
     * @param companyId 查询的公司id
     * @param sucFuc
     * @param errFuc
     * */
    this.getRentPayment = getRentPayment;

    this.createRentProtocol = createRentProtocol;

    this.checkRentPayment = checkRentPayment;
    
    this.getRentEndTime = getRentEndTime;


    /**
     * 获取缴租协议的计划项
     * @param companyId 公司id
     * @param rentId 租赁协议id
     * @param sucFuc
     * @param errFuc
     * */
    //绑定公司员工
    this.bindCompanyStaff = bindCompanyStaff;


    this.getRentPlanitemList = getRentPlanitemList;

    this.tenantsSubmitPay = tenantsSubmitPay;
    this.changeSubmitPay = changeSubmitPay;

    this.getChinaCitysJson = getChinaCitysJson;

    // 工具

    this.CLIENT_BASE_URL = CLIENT_BASE_URL;
    this.ALIYUN_URL = ALIYUN_URL;
    this.getAssign = assigned;
    this.cancleRentprotocol = cancleRentprotocol;
    



}]);
